var sio = require('socket.io')
        , mysql = require('mysql')
        , config = require('.././config')
        , utilities = require('./utilities');

var io;
var users;
var db;

//------------------------------------------------------------------------------
//  Connection Functions

exports.setDatabase = function(database) {
    db = database;
};

//------------------------------------------------------------------------------
//  Messaging Management Functions (Core Functionalities)

exports.initialize = function(HTTPServer) {
    this.io = sio.listen(HTTPServer);

    //  chat event listeners
    this.io.sockets.on('connection', function(socket) {

        socket.on('registerUser', function(name) {
            socket.nickname = name;

            var data = {type: chat_login, name: name};
            socket.broadcast.emit('announcement', data);
        });

        socket.on('sendMessage', function(data) {
            this.io.sockets.emit('newMessage', data);
        });

        socket.on('announcement', function(message) {
            var data = {name: 'server', message: message};

            this.io.sockets.emit('newMessage', data);
        });
    });
};

exports.updateAvailability = function(email, availability, callback) {
    var updateStatusQuery = "UPDATE user SET availability='" + availability + "' WHERE email = '" + email + "'";

    //  update the status of the user in the database                        
    db.query(updateStatusQuery, function(err) {
        if (err) {
            callback(err);
        } else {
            callback('Now Online');
        }
    });

};

/**
 *  Logs the user in the chat
 * @param {User} email   the email of the user to login
 * @param {User} password   the password of the user to login
 * @param {function} callback the callback function that will be called upon login success or failure
 * @returns {undefined}
 */
exports.login = function(email, password, callback) {
    if (!email) {
        throw new Error('Unspecified email when logging in.');
    }

    if (!password) {
        throw new Error('Unspecified password when logging in.');
    }

    var checkQuery = "SELECT (IF (password = '" + utilities.getMD5(password) + "', id, 'Incorrect')) data \n\
                    FROM user WHERE email = '" + email + "';";// \n\
//                    UPDATE user SET availability = (IF (password = '" + utilities.getMD5(password) + "', 'online', 'offline'))\n\
//                    WHERE email = '" + email + "';";

    db.query(checkQuery, function(err, result) {
        if (err) {
            callback(err);
        } else {
            if (result) {
                if (result.length >= 1) {
                    if (result[0].data === 'Incorrect') {
                        callback(new Error('Incorrect password'));
                    } else {                        
                        callback(result[0].data);
                    }
                } else {
                    callback(new Error('E-Mail not found'));
                }
            } else {
                callback(new Error('MySQL did not respond'));
            }
        }
    });
};

/**
 *  Logs the user out of the chat.
 * @param {type} email the user object that will login to the messaging server
 * @param {type} callback callback the callback function that will be called upon login success or failure
 * @returns {undefined}
 */
exports.logout = function(email, callback) {
    var query = "UPDATE user SET availability='offline' WHERE email = '" + email + "'";

    if (!email) {
        throw new Error('Unspecified email when logging in.');
    }

    //  make the user offline in the database
    db.query(query, function(err) {
        if (err) {
            callback(err);
        } else {
            callback('Now Offline');
        }
    });
};